package com.droidclaimcustomer.helper.asyntask;

import android.os.AsyncTask;
import android.util.Log;

public abstract class ProgressAsynTask<P, R> extends AsyncTask<P, Void, R> {

	private final String TAG = getClass().getName();

	private ICompleteListener taskCompletionListener;
	private IProgressTracker progressTracker;
	private Exception mostRecentException;
	private String taskId;
	
	public ProgressAsynTask(){
		progressTracker = null;
		taskCompletionListener = null;
	}
	
	public ProgressAsynTask(IProgressTracker progressTracker,
			ICompleteListener taskCompletionListener) {
		this.progressTracker = progressTracker;
		this.taskCompletionListener = taskCompletionListener;
	}
	
	public void setTaskCompletionListener(ICompleteListener taskCompletionListener) {
		this.taskCompletionListener = taskCompletionListener;
	}

	public void setProgressTracker(IProgressTracker progressTracker) {
		this.progressTracker = progressTracker;
	}
	
	public void setTaskId(String taskId){
		this.taskId = taskId;
	}
	
	public String getTaskId(){
		return taskId;
	}
	
	@Override
	protected void onPreExecute() {
		if (progressTracker != null) {
			this.progressTracker.onStartProgress();
		}
	}

	@Override
	protected R doInBackground(P... parameters) {
		mostRecentException = null;
		R result = null;

		try {
			result = performTaskInBackground(parameters);
		} catch (Exception e) {
			Log.e(TAG, "Failed to invoke the web service: ", e);
			mostRecentException = e;
		}

		return result;
	}

	protected abstract R performTaskInBackground(P... parameters) throws Exception;


	@Override
	protected void onPostExecute(R result) {
		if (progressTracker != null) {
			progressTracker.onStopProgress();
		}

		if (taskCompletionListener != null) {
			if (result == null || mostRecentException != null) {
				taskCompletionListener.onTaskFailed(taskId,mostRecentException);

			} else {
				taskCompletionListener.onTaskCompleteSuccess(taskId,result);
			}
		}

		progressTracker = null;
		taskCompletionListener = null;
	}
}
